//
//  OrgListTableViewController.m
//  Weiweiyunshi
//
//  Created by 张旭峰 on 2017/1/22.
//  Copyright © 2017年 王译. All rights reserved.
//

#import "OrgListTableViewController.h"
#import "UIColor+Addition.h"
#import "CustomLabel.h"
#import "WYNetWorkCache.h"
#import "WYHttpRequest.h"
#import "OrgModel.h"
#import "SubModel.h"
#import "PeopleModel.h"
#import "YYModel.h"
#import "OrginformationController.h"
#import "PersonImageTableViewCell.h"
#define URL @"http://210.72.239.121:8088/SSIL/OrganizationCache.do?userId=sunsiyuan"


enum cell{
    A,
    B,
    C,
} Cell;
@interface OrgListTableViewController ()<UITableViewDelegate,UITableViewDataSource>


@property(nonatomic,copy)NSArray<OrgModel*> * rightlmodelData;
@property(nonatomic,copy)NSString * company;
@property(nonatomic,strong)UILabel * headbutton;
@property(nonatomic,assign)NSInteger  counttt;
@property(nonatomic,copy)NSString * pdeptId;
@property(nonatomic,copy)NSMutableArray<id> * detailarray;
@property(nonatomic,copy)NSString * buttonTitle;
@property(nonatomic,copy)NSString * sectitle;
@property(nonatomic,copy)NSArray<id>* subright;
@property(nonatomic,assign)NSUInteger  lengtht;
@property(nonatomic,copy)NSString * pdeptName;


@end

@implementation OrgListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    Cell=A;
    
    [self setupUI];
    [self loadData];
    self.tableView.rowHeight=UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight=200;

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
     [self.tableView registerNib:[UINib nibWithNibName:@"PersonImageTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell3"];
    
}
-(void)setupUI
{
    UITableView *tableView= [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    tableView.dataSource = self;
    [self.view addSubview: tableView];
    self.tableView.delegate=self;
    self.tableView.dataSource = self;
    
    self.tableView = tableView;

    
    UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick)];
    CustomLabel *label = [[CustomLabel alloc] init];
    // 2. 将点击事件添加到label上
    [label addGestureRecognizer:labelTapGestureRecognizer];
    label.userInteractionEnabled = YES; // 可以理解为设置label可被点击
    NSString *str =@"上海易谷网络科技有限公司";
    label.text = str;
    [label setTintColor:[UIColor lightGrayColor]];
    label.font = [UIFont systemFontOfSize:15.0];
    label.numberOfLines = 0;
    label.backgroundColor=[UIColor colorWithRed:255 green:255 blue:255];

    
    CGSize titleSize = [str boundingRectWithSize:CGSizeMake(self.view.bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
    //    titleSize.height = 20;
    //    titleSize.width += 20;
    
    //    button.titleLabel.size = titleSize;
    
    
    
    label.frame=CGRectMake(0, 0, self.view.bounds.size.width, titleSize.height+10);
    label.edgeInsets = UIEdgeInsetsMake(8, 14, 8, 14);
    [label sizeToFit];
    self.headbutton = label;
    tableView.tableHeaderView = label;
    
    
}
-(void)labelClick{
    
    if(Cell ==B)
    {
        Cell=A;
       
//        [_headbutton setTitle:@"上海易谷网路科技有限公司" forState:UIControlStateNormal];
        _headbutton.text = @"上海易谷网络科技有限公司";
        [self.tableView reloadData];
         [_headbutton sizeToFit];
        self.tableView.tableHeaderView = _headbutton;
        
//        self.tableView.tableHeaderView=_headbutton;
    }else if(Cell == C)
    {
        Cell = B;
        
        
        CGSize titleSize = [_sectitle boundingRectWithSize:CGSizeMake(self.view.bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
        _headbutton.frame=CGRectMake(0, 0, self.view.bounds.size.width, titleSize.height+10);
        
        NSMutableAttributedString *stringgg333 = [[NSMutableAttributedString alloc]initWithString:_sectitle];
        
        NSRange blueRange = NSMakeRange(0, [[stringgg333 string]rangeOfString:@"-"].location);
        [stringgg333 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x0073dd] range:blueRange];
        [_headbutton setAttributedText:stringgg333];
//        _headbutton.text = _sectitle ;
//        _buttonTitle =_sectitle;
        [_headbutton sizeToFit];
        [self.tableView reloadData];
        self.tableView.tableHeaderView = _headbutton;
        
    }
    
}

-(void)loadData
{
    

    id response = [WYNetWorkCache cacheJsonWithURL:URL];
    if (response ==NULL) {
        [self request];
    }else{
        [self dataForWithJson:response];
    }

}
-(void)request{
    [WYHttpRequest getWithURLString:URL parameters:nil success:^(id responseObject) {
        [WYNetWorkCache save_asyncJsonResponseToCacheFile:responseObject andURL:URL completed:^(BOOL result) {
            if (result) {
                NSLog(@"写入成功");
            }else{
                NSLog(@"写入失败");
            }
        }];
        [self dataForWithJson:responseObject];
    }
                            failure:nil];
}


-(void)dataForWithJson:(id)response{
    NSArray *arr = response[@"info"];
    for (int i = 0; i<arr.count; i++) {
        NSArray *infoArr = arr[i];
        OrgModel *orgModel = [OrgModel yy_modelWithJSON:infoArr];
        [[OrgModel sharedSingleton] addObject:orgModel];
        for (int j = 0; j<orgModel.sub.count; j++) {
            NSArray *subArr = orgModel.sub[j];
            SubModel *subModel = [SubModel yy_modelWithJSON:subArr];
            [[SubModel sharedSingleton] addObject:subModel];
            for (int k = 0; k<subModel.people.count; k++) {
                NSArray *peoArr = subModel.people[k];
                PeopleModel *peoModel = [PeopleModel yy_modelWithJSON:peoArr];
                peoModel.deptName = subModel.deptName;
                peoModel.pdeptName = orgModel.pdeptName;
                [[PeopleModel sharedSingleton] addObject:peoModel];
//                [[PeopleModel sharedSingleton] addObject:subModel.deptName];
//                [[PeopleModel sharedSingleton] addObject:orgModel.pdeptName];
            }
        }
    }
    [self test];
}
-(void)test{
    
    
    self.rightlmodelData= [OrgModel sharedSingleton];
    
    [self.tableView reloadData];
}
-(void)loadData1:(NSInteger)indexpathrow
{
    
    NSArray<SubModel*> *array111= self.rightlmodelData[indexpathrow].sub;
    NSString *stringggg= self.rightlmodelData[indexpathrow].pdeptName;
    _pdeptName = stringggg;
    _lengtht = stringggg.length;
    _pdeptId = self.rightlmodelData[indexpathrow].pdeptId;
    NSString* stringgg2= [NSString stringWithFormat:@"上海易谷网络科技有限公司 - %@",stringggg];
     NSMutableAttributedString *stringgg33 = [[NSMutableAttributedString alloc]initWithString:stringgg2];
    _sectitle = stringgg2;
    _buttonTitle = stringgg2;
    
    NSRange blueRange = NSMakeRange(0, [[stringgg33 string]rangeOfString:@"-"].location);
    [stringgg33 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x0073dd] range:blueRange];
    
    
    
    CGSize titleSize = [_buttonTitle boundingRectWithSize:CGSizeMake(self.view.bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
   
    
//    _headbutton.text = stringgg2;
    
    _headbutton.frame=CGRectMake(0, 0, self.view.bounds.size.width, titleSize.height+10);
    
    
    
    self.subright = array111;
    self.counttt =array111.count;
    [_headbutton sizeToFit];
    [_headbutton setAttributedText:stringgg33];
    [self.tableView reloadData];
    self.tableView.tableHeaderView = _headbutton;
    
}


-(void)loadData2:(NSInteger)indexpathrow
{
    
    
    NSString *stringf = self.subright[indexpathrow][@"deptId"];
    NSString *stringbutton = self.subright[indexpathrow][@"deptName"];
    NSLog(@"--->%@",stringbutton);
    
    NSString *string88 = [NSString stringWithFormat:@"%@ - %@",_buttonTitle,stringbutton];
    
     NSString *string89 = [NSString stringWithFormat:@"%@ - %@",_buttonTitle,stringbutton];
    NSLog(@"---->>>>%@",string89);
    NSMutableAttributedString *string44=[[NSMutableAttributedString alloc]initWithString:string88 ];
    NSLog(@"-----%@",string44);
    NSRange blueRange = NSMakeRange(14, _lengtht+1);
    [string44 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x0073dd] range:blueRange];

    CGSize titleSize = [string89 boundingRectWithSize:CGSizeMake(self.view.bounds.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
    //    titleSize.height = 20;
    //    titleSize.width += 20;
    
    //    button.titleLabel.size = titleSize;
    
    
//    _buttonTitle = stringbutton;
    
    _headbutton.frame=CGRectMake(0, 0, self.view.bounds.size.width, titleSize.height+10);
    
    self.detailarray = self.subright[indexpathrow][@"people"];
    
    self.counttt = _detailarray.count;
    [_headbutton setAttributedText:string44];
    [_headbutton sizeToFit];
    
    [self.tableView reloadData];
    self.tableView.tableHeaderView=_headbutton;

    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if(Cell == A)
    {
        return self.rightlmodelData.count;
    }else if(Cell == B)
    {
        return self.subright.count;
    }else{
        return self.counttt;
        
    }

    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cellee = [tableView dequeueReusableCellWithIdentifier:@"cell"forIndexPath:indexPath];
    
    if(Cell ==A)
    {
        NSString *str = self.rightlmodelData[indexPath.row].pdeptName;
        NSArray *arrayyy=self.rightlmodelData[indexPath.row].sub;
        cellee.textLabel.text=[NSString stringWithFormat:@"%@  (%ld)",str,arrayyy.count];
    }
    else if(Cell == B)
    {
        cellee.textLabel.text=self.subright[indexPath.row][@"deptName"];
        
    }
    else
    {
        PersonImageTableViewCell * cell3 =[tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
        
        
//        cellee.textLabel.text = _detailarray[indexPath.row][@"userName"];
        cell3.PersonName.text = _detailarray[indexPath.row][@"userName"];
        
        [cell3.PersonimageView sd_setImageWithURL:[NSURL URLWithString:_detailarray[indexPath.row][@"img"]]];
        cellee.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell3;
        
        
//        [cellee.imageView sd_setImageWithURL:[NSURL URLWithString:_detailarray[indexPath.row][@"img"]]];
    }
    
    cellee.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cellee;

}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(Cell ==A)
    {
        Cell = B;
        [self loadData1:indexPath.row];
        
        
    }
    else if(Cell ==B)
    {
        
        Cell = C;
        [self loadData2:indexPath.row];
    }
    else{
        OrginformationController *orinforVC = [[OrginformationController alloc]init];
        orinforVC.userName =_detailarray[indexPath.row][@"userName"];
        orinforVC.deptName =_pdeptName;

        orinforVC.pdeptName = _buttonTitle;
        orinforVC.email =_detailarray[indexPath.row][@"email"];
        orinforVC.mobile =_detailarray[indexPath.row][@"mobile"];
        orinforVC.img =_detailarray[indexPath.row][@"img"];
        orinforVC.vidyoKey = _detailarray[indexPath.row][@"vidyoKey"];
        orinforVC.vidyoURL = _detailarray[indexPath.row][@"vidyoURL"];
        orinforVC.domainName = _detailarray[indexPath.row][@"domainName"];
        [self.navigationController pushViewController: orinforVC animated:YES];
        
    }
}

@end
